package com.lanou.sfu.songforu.mv;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.lanou.sfu.songforu.R;
import com.lanou.sfu.songforu.constant.Url;
import com.lanou.sfu.songforu.singleton.VolleySingleton;
import com.lanou.sfu.songforu.tools.SwipeRefreshLoadingLayout;

import java.util.List;

/**
 * Created by dllo on 15/10/21.
 */
public class MVFragment extends Fragment implements SwipeRefreshLoadingLayout.OnLoadListener, SwipeRefreshLoadingLayout.OnRefreshListener, AdapterView.OnItemClickListener {
    private VolleySingleton volleySingleton;
    private MVFragmentAdapter adapter;
    private SwipeRefreshLoadingLayout refreshLoadingLayout; // 定义下拉组件刷新
    private GridView gridView;
    private int page;
    private String urls;
    private String url;
    private String num;
    private ProgressDialog dialog;
    private String str;

    private static SparseArray<MVFragment> fragments = new SparseArray<>();

    public static MVFragment getFragment(int position, String url, String num) {

        MVFragment f = fragments.get(position);
        if (f == null) {
            f = new MVFragment();

            // 传送数据
            Bundle bundle = new Bundle();
            bundle.putString("arg", url);
            bundle.putString("arg1", num);
            f.setArguments(bundle);
        }
        fragments.put(position, f);
        return f;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_hot_mv, null);

        // 初始化
        refreshLoadingLayout = (SwipeRefreshLoadingLayout) view.findViewById(R.id.refreshLayout);
        gridView = (GridView) view.findViewById(R.id.hot_mv_gridview);

        // 初始化dialog
        dialog = new ProgressDialog(getActivity());
        dialog.setMessage(getActivity().getString(R.string.DATA_LOADING));
        dialog.show();

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //获得数据
        Bundle bundle = getArguments();
        url = bundle.getString("arg");
        num = bundle.getString("arg1");
        page = 1;
        urls = url + num + Url.MV_PAGE + page + Url.MV_SIZE;
        init(getActivity());
        getDatas(urls);
//        http://api.dongting.com/song/video/type/0?order=2&page=1&size=12
        // 刷新加载组件监听
        refreshLoadingLayout.setOnLoadListener(this);
        refreshLoadingLayout.setOnRefreshListener(this);
        gridView.setOnItemClickListener(this);
    }


    //初始化数据
    public void init(Context mContext) {
        volleySingleton = VolleySingleton.getInstance(mContext);
    }

    // 从网上拉取数据
    public void getDatas(String url) {
        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }

                Gson gson = new Gson();
                TTMV entity = gson.fromJson(response, TTMV.class);
                List<TTMV.DataEntity> entityList = entity.getData();
                if (entityList != null) {
                    adapter = new MVFragmentAdapter(getActivity(), entityList);
                }
                gridView.setAdapter(adapter);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
        volleySingleton.addQueue(request);
    }


    @Override
    public void onLoad() {
        page += 1;
        String newUrl = url + num + Url.MV_PAGE + page + Url.MV_SIZE;
        StringRequest request = new StringRequest(newUrl, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                TTMV entity = gson.fromJson(response, TTMV.class);
                List<TTMV.DataEntity> entityList = entity.getData();

                if (entityList != null) {
                    adapter.addDatas(entityList);
                }
                refreshLoadingLayout.setLoading(false);
                Toast.makeText(getActivity(), R.string.LOAD_SUCCESS, Toast.LENGTH_SHORT).show();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
        volleySingleton.addQueue(request);
    }

    @Override
    public void onRefresh() {
        page = 1;
        String newUrl = url + num + Url.MV_PAGE + page + Url.MV_SIZE;
        StringRequest request = new StringRequest(newUrl, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                TTMV entity = gson.fromJson(response, TTMV.class);
                List<TTMV.DataEntity> entityList = entity.getData();

                if (entityList != null) {
                    adapter.refreshDatas(entityList);
                }
                refreshLoadingLayout.setRefreshing(false);
                Toast.makeText(getActivity(), R.string.REFRESH_SECCESS, Toast.LENGTH_SHORT).show();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
        volleySingleton.addQueue(request);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        TTMV.DataEntity result = (TTMV.DataEntity) parent.getItemAtPosition(position);
        String url =  result.getMvList().get(0).getUrl();
        if (url != null) {
            Intent intent = new Intent(getActivity(),VideoActivity.class);
            intent.putExtra("url",url);
            startActivity(intent);
        }


    }
}
